package com.mantru.iotpot.Adapter

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.res.ColorStateList
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.Switch
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity.INPUT_METHOD_SERVICE
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.graphics.toColorInt
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.mantru.iotpot.Adapter.Base.AppAdapter
import com.mantru.iotpot.Adapter.Base.AppHolder
import com.mantru.iotpot.ApplicationClass
import com.mantru.iotpot.Bean.DishesCreateBean
import com.mantru.iotpot.Bean.DishesCreateFoodBean
import com.mantru.iotpot.Bean.DishesCreateSauceBean
import com.mantru.iotpot.Dialog.DeleteStepDialog
import com.mantru.iotpot.R
import com.mantru.iotpot.Util.TimeUtil
import com.mantru.iotpot.Util.ToastUtils
import com.mantru.iotpot.dishes.DishesCreateActivity

class DishesCreateAdapter(var context: Context, layoutResId: Int, var data: MutableList<DishesCreateBean>): AppAdapter<DishesCreateBean>(context, layoutResId, data) {

    inner class DishesCreateViewHolder(itemView: View) : AppHolder(itemView) {
        var textWatcher: TextWatcher? = null
        var heatSeekBarChangeListener: OnSeekBarChangeListener? = null
        var speedSeekBarChangeListener: OnSeekBarChangeListener? = null
        var switchChangeListener: CompoundButton.OnCheckedChangeListener? = null
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AppHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.adapter_dishes_create, parent, false)
        return DishesCreateViewHolder(view)
    }

    private var dishesCreateListener: DishesCreateListener? = null
    fun setDishesCreateListener(dishesCreateListener: DishesCreateListener?) {
        this.dishesCreateListener = dishesCreateListener
    }
    interface DishesCreateListener {
        fun onDelete(position: Int)
        fun setTime(position: Int, value: String)
        fun setHeat(position: Int, value: String)
        fun setSpeed(position: Int, value: String)
        fun setForward(position: Int, value: String)
        fun setUp(position: Int, value: String)
        fun setNozzleNameList(position: Int, value: MutableList<String>)
        fun setNozzleValueList(position: Int, value: MutableList<String>)
        fun setCassetteNameList(position: Int, value: MutableList<String>)
        fun setCassetteValueList(position: Int, value: MutableList<String>)
        fun setAddFood(position: Int, value: String)
        fun setSwitchState(position: Int, value: String)
    }
    var dishesCreateSauceList: MutableList<DishesCreateSauceBean> = mutableListOf()
    var dishesCreateSauceBeans: MutableList<DishesCreateSauceBean> = mutableListOf()
    var dishesCreateFoodList: MutableList<DishesCreateFoodBean> = mutableListOf()
    var dishesCreateFoodBeans: MutableList<DishesCreateFoodBean> = mutableListOf()
    var dishesCreateSauceAdapter: DishesCreateSauceAdapter? = null
    var dishesCreateFoodAdapter: DishesCreateFoodAdapter? = null
    var foodLength = 0

    override fun convert(holder: AppHolder?, position: Int, item: DishesCreateBean) {
        var time: EditText? = null
        var heatSeekBar: SeekBar? = null
        var speedSeekBar: SeekBar? = null
        var forward: TextView? = null
        var reverse: TextView? = null
        var forwardAndReverse: TextView? = null
        var upLayout: ConstraintLayout? = null
        var upText: TextView? = null
        var downLayout: ConstraintLayout? = null
        var downText: TextView? = null
        var sauceRecyclerview: RecyclerView? = null
        var foodRecyclerview: RecyclerView? = null
        var leaveSwitch: Switch? = null
        var deleteStepDialog: DeleteStepDialog? = null
        val viewHolder = holder as? DishesCreateViewHolder ?: return
        var normalColor: ColorStateList? = null
        var minColor: ColorStateList? = null
        normalColor = ContextCompat.getColorStateList(
            context,
            R.color.normal_seekbar_color
        ) // 正常颜色
        minColor = ContextCompat.getColorStateList(
            context,
            R.color.min_seekbar_color
        ) // 最小值颜色

        //对食材数据进行特殊处理
        val boxNameListList = (context as? DishesCreateActivity)?.viewModel?.box_name_List_List?.get() ?: mutableListOf()
        val currentBoxNameList = boxNameListList.getOrNull(position) ?: mutableListOf()
        // 将当前的 box_name_List_List 按 position 设置给 item.foodNameList
        item.foodNameList = currentBoxNameList.toMutableList()

        val sauceNameList = item.sauceNameList.toMutableList()
        val sauceValueList = item.sauceValueList.toMutableList()
        val foodNameList = item.foodNameList.toMutableList()
        val foodValueList = item.foodValueList.toMutableList()

        //持续时间
        time = holder?.getView<EditText>(R.id.adapter_dishes_create_time_choose_num)
        viewHolder.textWatcher?.let {
            time!!.removeTextChangedListener(it)
        }
        //加热滑动条
        heatSeekBar = holder?.getView<SeekBar>(R.id.adapter_dishes_create_heat_heat_seekBar)
        heatSeekBar?.setOnSeekBarChangeListener(null)
        val fireValue = item.fire_value.toIntOrNull() ?: 0
        heatSeekBar?.progress = fireValue + 1 // UI显示值比实际值大1
        // 根据进度切换颜色
        if (heatSeekBar?.progress!! == 1) {
            heatSeekBar.progressTintList = minColor // 设置为最小值颜色
        } else {
            heatSeekBar.progressTintList = normalColor // 设置为正常颜色
        }
        //转速滑动条
        speedSeekBar = holder?.getView<SeekBar>(R.id.adapter_dishes_create_heat_speed_seekBar)
        speedSeekBar?.setOnSeekBarChangeListener(null)
        val speedValue = item.gripper_speed_value.toIntOrNull() ?: 0
        speedSeekBar?.progress = speedValue + 1 // UI显示值比实际值大1
        // 根据进度切换颜色
        if (speedSeekBar?.progress!! == 1) {
            speedSeekBar.progressTintList = minColor // 设置为最小值颜色
        } else {
            speedSeekBar.progressTintList = normalColor // 设置为正常颜色
        }
        //顺时针按钮
        forward = holder?.getView<TextView>(R.id.adapter_dishes_create_heat_forward)
        //逆时针按钮
        reverse = holder?.getView<TextView>(R.id.adapter_dishes_create_heat_reverse)
        //正反转按钮
        forwardAndReverse = holder?.getView<TextView>(R.id.adapter_dishes_create_heat_forward_and_reverse)
        //抬起按钮
        upLayout = holder?.getView<ConstraintLayout>(R.id.adapter_dishes_create_heat_up)
        //抬起文字
        upText = holder?.getView<TextView>(R.id.adapter_dishes_create_heat_up_text)
        //放下按钮
        downLayout = holder?.getView<ConstraintLayout>(R.id.adapter_dishes_create_heat_down)
        //放下文字
        downText = holder?.getView<TextView>(R.id.adapter_dishes_create_heat_down_text)
        //调味料recyclerview
        sauceRecyclerview = holder?.getView<RecyclerView>(R.id.adapter_dishes_create_sauce_recyclerview)
        //固体料盒recyclerview
        foodRecyclerview = holder?.getView<RecyclerView>(R.id.adapter_dishes_create_food_container_recyclerview)
        //避让方式滑块
        leaveSwitch = holder?.getView<Switch>(R.id.adapter_dishes_create_food_leave_switch)
        leaveSwitch?.setOnCheckedChangeListener(null)
        leaveSwitch?.isChecked = item.box_need_avoid != "0"

        holder?.setVisibility(R.id.adapter_dishes_create_heat, item.steep_type == "1")
            ?.setVisibility(R.id.adapter_dishes_create_sauce, item.steep_type == "2")
            ?.setVisibility(R.id.adapter_dishes_create_food, item.steep_type == "3")
            ?.setText(R.id.adapter_dishes_create_title, setTitle(item.steep_index, item.steep_type))//填入标题
            ?.setText(R.id.adapter_dishes_create_time_choose_num, item.time_long)//填入时长
            ?.setProgress(R.id.adapter_dishes_create_heat_heat_seekBar, item.fire_value.toInt() + 1)//填入火力
            ?.setProgress(R.id.adapter_dishes_create_heat_speed_seekBar, item.gripper_speed_value.toInt() + 1)//填入转速
            ?.setBackground(R.id.adapter_dishes_create_heat_forward, setButtonIsChooseBackground(item.gripper_rotation_value, "顺时针"))//填入正反向数据
            ?.setBackground(R.id.adapter_dishes_create_heat_reverse, setButtonIsChooseBackground(item.gripper_rotation_value, "逆时针"))
            ?.setBackground(R.id.adapter_dishes_create_heat_forward_and_reverse, setButtonIsChooseBackground(item.gripper_rotation_value, "正反转"))
            ?.setBackground(R.id.adapter_dishes_create_heat_up, setButtonIsChooseBackground(item.gripper_position_value, "抬起"))//填入搅拌子状态
            ?.setBackground(R.id.adapter_dishes_create_heat_down, setButtonIsChooseBackground(item.gripper_position_value, "放下"))
            ?.setOnClickListener(R.id.adapter_dishes_create_delete){//监听删除按钮
                //弹出删除提示弹窗
                if ( deleteStepDialog == null || !deleteStepDialog!!.isShowing ){
                    deleteStepDialog = DeleteStepDialog(context, R.style.Common_Dialog)
                    deleteStepDialog!!.setDeleteStepDialogListener(object : DeleteStepDialog.DeleteStepDialogListener{
                        override fun confirm() {
                            dishesCreateListener?.onDelete(position)
                        }
                    })
                    deleteStepDialog!!.show()
                }
            }
            ?.setOnClickListener(R.id.adapter_dishes_create_heat_forward){//监听转向按钮
                dishesCreateListener?.setForward(position, "0")
                forward!!.setBackgroundResource(R.drawable.radius8_1151e4)
                reverse!!.setBackgroundResource(R.drawable.radius8_1affffff)
                forwardAndReverse!!.setBackgroundResource(R.drawable.radius8_1affffff)
                item.gripper_rotation_value = "0"
            }
            ?.setOnClickListener(R.id.adapter_dishes_create_heat_reverse){
                dishesCreateListener?.setForward(position, "1")
                forward!!.setBackgroundResource(R.drawable.radius8_1affffff)
                reverse!!.setBackgroundResource(R.drawable.radius8_1151e4)
                forwardAndReverse!!.setBackgroundResource(R.drawable.radius8_1affffff)
                item.gripper_rotation_value = "1"
            }
            ?.setOnClickListener(R.id.adapter_dishes_create_heat_forward_and_reverse){
                dishesCreateListener?.setForward(position, "2")
                forward!!.setBackgroundResource(R.drawable.radius8_1affffff)
                reverse!!.setBackgroundResource(R.drawable.radius8_1affffff)
                forwardAndReverse!!.setBackgroundResource(R.drawable.radius8_1151e4)
                item.gripper_rotation_value = "2"
            }
            ?.setOnClickListener(R.id.adapter_dishes_create_heat_up){//监听搅拌子状态
                dishesCreateListener?.setUp(position, "2")
                upLayout!!.setBackgroundResource(R.drawable.radius8_1151e4)
                downLayout!!.setBackgroundResource(R.drawable.radius8_1affffff)
                upText!!.setTextColor("#FFFFFF".toColorInt())
                downText!!.setTextColor("#66FFFFFF".toColorInt())
                item.gripper_position_value = "2"
            }
            ?.setOnClickListener(R.id.adapter_dishes_create_heat_down){
                dishesCreateListener?.setUp(position, "1")
                upLayout!!.setBackgroundResource(R.drawable.radius8_1affffff)
                downLayout!!.setBackgroundResource(R.drawable.radius8_1151e4)
                upText!!.setTextColor("#66FFFFFF".toColorInt())
                downText!!.setTextColor("#FFFFFF".toColorInt())
                item.gripper_position_value = "1"
            }
            ?.setOnClickListener(R.id.adapter_dishes_create_sauce_add){//监听调味料添加按钮
                //如果最新一项没填写，则不允许添加
                if ( sauceNameList[sauceNameList.size - 1].isEmpty() || sauceValueList[sauceValueList.size - 1].isEmpty() ){
//                    Toast.makeText(context, "请先完善当前步骤的调味料数据", Toast.LENGTH_SHORT).show()
                    ToastUtils.show(context, "请先完善当前步骤的调味料数据")
                    return@setOnClickListener
                }
                //添加一项数据
                addSauceItem(item, position, sauceNameList, sauceValueList, "新增列表")
            }
            ?.setOnClickListener(R.id.adapter_dishes_create_food_container_add){//食材添加按钮
                //如果最新一项没填写，则不允许添加
                if ( foodNameList[foodNameList.size - 1].isEmpty() || foodValueList[foodValueList.size - 1].isEmpty() ){
//                    Toast.makeText(context, "请先完善当前步骤的食材数据", Toast.LENGTH_SHORT).show()
                    ToastUtils.show(context, "请先完善当前步骤的食材数据")
                    return@setOnClickListener
                }
                //添加一项数据
                addFoodItem(item, position, foodNameList, foodValueList, "新增列表")
            }
            ?.setText(R.id.adapter_dishes_create_food_general_choose_num, getAddFoodType(item.box_release_type))//填入投菜方式
            ?.setTextColor(R.id.adapter_dishes_create_food_general_choose_num, getAddFoodColor(item.box_release_type))
            ?.setOnClickListener(R.id.adapter_dishes_create_food_general_choose){//监听投菜方式选择
                showAddFoodDialog(position, holder, item)
            }

        //初始化recyclerview
        setRecyclerView(sauceNameList, position, sauceRecyclerview!!, foodRecyclerview!!)
        //设置参数
        //设置当前项的持续时间
        val newWatcher = object : TextWatcher {
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if ( s.toString().isNotEmpty() ){
                    item.time_long = s.toString()
                    item.time_value = TimeUtil.formatDuration(s.toString().toInt(), "mm:ss")
                    dishesCreateListener?.setTime(position, s.toString())
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun afterTextChanged(s: Editable?) {}
        }
        time!!.addTextChangedListener(newWatcher)

        time.setOnEditorActionListener { v: TextView, actionId: Int, event: KeyEvent? ->
            // 检查是否是按下 Enter 键或者完成操作
            if ((event != null && event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER)
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_DONE
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_NEXT
                || actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEND) {

                // 获取输入法管理器
                val imm = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager?
                // 隐藏软键盘
                imm?.hideSoftInputFromWindow(v.windowToken, 0)
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }

        viewHolder.textWatcher = newWatcher

        //设置当前项火力
        val newHeatBar = object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                // 根据进度切换颜色
                if (progress == 1) {
                    seekBar.progressTintList = minColor // 设置为最小值颜色
                } else {
                    seekBar.progressTintList = normalColor // 设置为正常颜色
                }
                if (!fromUser) return // 仅处理用户操作
                val validProgress = progress.coerceAtLeast(1)
                if (progress != validProgress) {
                    seekBar.progress = validProgress
                    return
                }
                val actualValue = (validProgress - 1).toString()
                dishesCreateListener?.setHeat(position, actualValue)
                item.fire_value = actualValue
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        }
        heatSeekBar?.setOnSeekBarChangeListener(newHeatBar)
        viewHolder.heatSeekBarChangeListener = newHeatBar

        //设置转速
        val newSpeedBar = object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                // 根据进度切换颜色
                if (progress == 1) {
                    seekBar.progressTintList = minColor // 设置为最小值颜色
                } else {
                    seekBar.progressTintList = normalColor // 设置为正常颜色
                }
                if (!fromUser) return // 仅处理用户操作
                val validProgress = progress.coerceAtLeast(1)
                if (progress != validProgress) {
                    seekBar.progress = validProgress
                    return
                }
                val actualValue = (validProgress - 1).toString()
                dishesCreateListener?.setSpeed(position, actualValue)
                item.gripper_speed_value = actualValue
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        }
        speedSeekBar?.setOnSeekBarChangeListener(newSpeedBar)
        viewHolder.speedSeekBarChangeListener = newSpeedBar

        //设置投放避让滑块状态
        val newSwitchListener = CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            val value = if (isChecked) "1" else "0"
            // 确保 position 有效（使用绝对位置）
            val adapterPosition = holder?.adapterPosition ?: return@OnCheckedChangeListener
            if (adapterPosition != RecyclerView.NO_POSITION) {
                dishesCreateListener?.setSwitchState(adapterPosition, value)
                data.getOrNull(adapterPosition)?.box_need_avoid = value
            }
        }
        leaveSwitch?.setOnCheckedChangeListener(newSwitchListener)
        viewHolder.switchChangeListener = newSwitchListener

        setValue(holder, item, position, sauceNameList, sauceValueList, foodNameList, foodValueList)
        if ( item.steep_type == "2" ){
            //添加一项数据
            addSauceItem(item, position, sauceNameList, sauceValueList, "初始化")
        } else if ( item.steep_type == "3" ){
            //添加一项数据
            addFoodItem(item, position, foodNameList, foodValueList, "初始化")
        }
    }

    //填入标题
    private fun setTitle(index: String, type:String): String {
        return when (type){
            "1" ->{
                "步骤$index: 加热设置"
            }
            "2" ->{
                "步骤$index: 调味料"
            }
            "3" ->{
                "步骤$index: 固体料盒"
            }
            else ->{
                ""
            }
        }
    }

    //设置背景颜色
    //如果按钮和资源显示一一对应，则返回蓝色背景，否则返回灰色背景
    private fun setButtonIsChooseBackground(value: String, type: String): Int {
        val key = "$type-$value"
        return when (key) {
            "顺时针-0", "逆时针-1", "正反转-2", "抬起-2", "放下-1"-> R.drawable.radius8_1151e4
            else -> R.drawable.radius8_1affffff
        }
    }

    //初始化recyclerview
    private fun setRecyclerView(sauceNameList: MutableList<String>, position: Int, sauceRecyclerview: RecyclerView, foodRecyclerview: RecyclerView){
        dishesCreateSauceAdapter = DishesCreateSauceAdapter(context, R.layout.adapter_dishes_create_sauce, dishesCreateSauceList, sauceNameList)
        sauceRecyclerview.apply {
            setLayoutManager(StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL))
            adapter = dishesCreateSauceAdapter
            sauceRecyclerview.isNestedScrollingEnabled = false
        }

        dishesCreateFoodAdapter = DishesCreateFoodAdapter(context, R.layout.adapter_dishes_create_food, dishesCreateFoodList, position)
        foodRecyclerview.apply {
            setLayoutManager(StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL))
            adapter = dishesCreateFoodAdapter
            foodRecyclerview.isNestedScrollingEnabled = false
        }
    }

    //设置参数
    private fun setValue(holder: AppHolder?, item: DishesCreateBean, position: Int, sauceNameList: MutableList<String>, sauceValueList: MutableList<String>, foodNameList: MutableList<String>, foodValueList: MutableList<String>){

        //设置调味料填写内容
        dishesCreateSauceAdapter!!.setDishesCreateSauceListener(object : DishesCreateSauceAdapter.DishesCreateSauceListener{
            override fun onDelete(listPosition: Int) {
                sauceNameList.removeAt(listPosition)
                sauceValueList.removeAt(listPosition)
                item.sauceNameList = sauceNameList.toMutableList() // 确保同步到item // 同步到DishesCreateBean
                item.sauceValueList = sauceValueList.toMutableList() // 确保同步到item // 同步到DishesCreateBean
                putSauceData(sauceNameList, sauceValueList)
                if ( sauceNameList.isNotEmpty() ){
                    for ( i in 0 until sauceNameList.size){
                        if ( sauceNameList[i].isEmpty() ){
                            return
                        }
                    }
                    dishesCreateListener?.setNozzleNameList(position, sauceNameList)
                    dishesCreateListener?.setNozzleValueList(position, sauceValueList)
                }
                // 通知外层 Adapter 刷新
                notifyItemChanged(position)
            }

            override fun setName(listPosition: Int, value: String) {
                if ( sauceNameList.isNotEmpty() ){
                    sauceNameList[listPosition] = value
                    item.sauceNameList = sauceNameList.toMutableList() // 确保同步到item // 同步到DishesCreateBean

                    var timeLimitSet = 0
                    if ( item.sauceNameList.size == item.sauceValueList.size && !item.sauceNameList.contains("") && !item.sauceValueList.contains("") ){
                        val applicationClass: ApplicationClass = context.applicationContext as ApplicationClass
                        for ( i in 0 until item.sauceNameList.size ){
                            var timeLimitItemSet = 0
                            when (item.sauceNameList[i]){
                                "生抽" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(1, item.sauceValueList[i].toInt())
                                }
                                "老抽" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(2, item.sauceValueList[i].toInt())
                                }
                                "蚝油" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(3, item.sauceValueList[i].toInt())
                                }
                                "动物油" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(4, item.sauceValueList[i].toInt())
                                }
                                "植物油" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(5, item.sauceValueList[i].toInt())
                                }
                                "盐水" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(6, item.sauceValueList[i].toInt())
                                }
                                "醋" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(7, item.sauceValueList[i].toInt())
                                }
                                "淀粉水" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(8, item.sauceValueList[i].toInt())
                                }
                                "烹饪水" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(9, item.sauceValueList[i].toInt())
                                }
//                                "烹饪水" ->{
//                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(10, item.sauceValueList[i].toInt())
//                                }
//                                "洗锅水" ->{
//                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(11, item.sauceValueList[i].toInt())
//                                }
                            }
                            if ( timeLimitItemSet > timeLimitSet ){
                                timeLimitSet = timeLimitItemSet
                            }
                        }
                    }
                    if ( item.time_long.isEmpty() ){
                        item.time_long = "0"
                    }
                    if ( item.time_long.isNotEmpty() && item.time_long.toInt() < timeLimitSet ){
                        item.time_long = timeLimitSet.toString()
                        item.time_value = TimeUtil.formatDuration(timeLimitSet.toString().toInt(), "mm:ss")
                        dishesCreateListener?.setTime(position, timeLimitSet.toString())
                        // 通知外层 Adapter 刷新
                        notifyItemChanged(position)
                    }

                    dishesCreateListener?.setNozzleNameList(position, sauceNameList)
                    dishesCreateListener?.setNozzleValueList(position, sauceValueList)
                }
            }

            override fun setValue(listPosition: Int, value: String) {
                if ( sauceNameList.isNotEmpty() ){//保证名称和数量列表长度相同
                    sauceValueList[listPosition] = value
                    item.sauceValueList = sauceValueList.toMutableList() // 确保同步到item // 同步到DishesCreateBean

                    var timeLimitSet = 0
                    if ( item.sauceNameList.size == item.sauceValueList.size && !item.sauceNameList.contains("") && !item.sauceValueList.contains("") ){
                        val applicationClass: ApplicationClass = context.applicationContext as ApplicationClass
                        for ( i in 0 until item.sauceNameList.size ){
                            var timeLimitItemSet = 0
                            when (item.sauceNameList[i]){
                                "生抽" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(1, item.sauceValueList[i].toInt())
                                }
                                "老抽" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(2, item.sauceValueList[i].toInt())
                                }
                                "蚝油" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(3, item.sauceValueList[i].toInt())
                                }
                                "动物油" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(4, item.sauceValueList[i].toInt())
                                }
                                "植物油" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(5, item.sauceValueList[i].toInt())
                                }
                                "盐水" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(6, item.sauceValueList[i].toInt())
                                }
                                "醋" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(7, item.sauceValueList[i].toInt())
                                }
                                "淀粉水" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(8, item.sauceValueList[i].toInt())
                                }
                                "烹饪水" ->{
                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(9, item.sauceValueList[i].toInt())
                                }
//                                "烹饪水" ->{
//                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(10, item.sauceValueList[i].toInt())
//                                }
//                                "洗锅水" ->{
//                                    timeLimitItemSet = applicationClass.Device_Nozzle_Weight_2_Time(11, item.sauceValueList[i].toInt())
//                                }
                            }
                            if ( timeLimitItemSet > timeLimitSet ){
                                timeLimitSet = timeLimitItemSet
                            }
                        }
                    }
                    if ( item.time_long.isEmpty() ){
                        item.time_long = "0"
                    }
                    if ( item.time_long.isNotEmpty() && item.time_long.toInt() < timeLimitSet ){
                        item.time_long = timeLimitSet.toString()
                        item.time_value = TimeUtil.formatDuration(timeLimitSet.toString().toInt(), "mm:ss")
                        dishesCreateListener?.setTime(position, timeLimitSet.toString())
                        // 通知外层 Adapter 刷新
                        val timeEditText = holder?.getView<EditText>(R.id.adapter_dishes_create_time_choose_num)
                        timeEditText?.setText(timeLimitSet.toString())
                    }

                    dishesCreateListener?.setNozzleNameList(position, sauceNameList)
                    dishesCreateListener?.setNozzleValueList(position, sauceValueList)
                }
            }
        })

        //设置食材投放
        dishesCreateFoodAdapter!!.setDishesCreateFoodListener(object : DishesCreateFoodAdapter.DishesCreateFoodListener{
            override fun onDelete(listPosition: Int) {
                foodNameList.removeAt(listPosition)
                foodValueList.removeAt(listPosition)
                item.foodNameList = foodNameList.toMutableList() // 确保同步到item // 同步到DishesCreateBean
                item.foodValueList = foodValueList.toMutableList() // 确保同步到item // 同步到DishesCreateBean

                putFoodData(foodNameList, foodValueList)
                if ( foodNameList.isNotEmpty() ){
                    for ( i in 0 until foodNameList.size){
                        if ( foodNameList[i].isEmpty() ){
                            return
                        }
                    }
                    dishesCreateListener?.setCassetteNameList(position, foodNameList)
                    dishesCreateListener?.setCassetteValueList(position, foodValueList)
                }
                // 通知外层 Adapter 刷新
                notifyItemChanged(position)
            }

            override fun setValue(listPosition: Int, value: String) {
                if ( foodValueList.isNotEmpty() ){
                    foodValueList[listPosition] = value
                    item.foodValueList = foodValueList.toMutableList() // 确保同步到item // 同步到DishesCreateBean

//                    var timeLimitSet = 0
//                    if ( item.foodNameList.size == item.foodValueList.size && !item.foodNameList.contains("") && !item.foodValueList.contains("") ){
//                        val applicationClass: ApplicationClass = context.applicationContext as ApplicationClass
//                        var boxUsedNum = 0
//                        if ( item.foodNameList.isEmpty() ){
//                            boxUsedNum = foodLength + 1
//                        } else {
//                            boxUsedNum = foodLength
//                        }
//                        var releaseType = 1//默认为1
//                        if ( item.box_release_type.isNotEmpty() ){
//                            releaseType = item.box_release_type.toInt()
//                        }
//                        val timeLimitItemSet = applicationClass.Device_BoxThrow_2_Time(boxUsedNum, releaseType)
//                        if ( timeLimitItemSet > timeLimitSet ){
//                            timeLimitSet = timeLimitItemSet
//                        }
//                    }
//                    if ( item.time_long.isEmpty() ){
//                        item.time_long = "0"
//                    }
//                    if ( item.time_long.isNotEmpty() ){
//                        item.time_long = timeLimitSet.toString()
//                        item.time_value = TimeUtil.formatDuration(timeLimitSet.toString().toInt(), "mm:ss")
//                        dishesCreateListener?.setTime(position, timeLimitSet.toString())
//                        // 通知外层 Adapter 刷新
//                        val timeEditText = holder?.getView<EditText>(R.id.adapter_dishes_create_time_choose_num)
//                        timeEditText?.setText(timeLimitSet.toString())
//                    }

                    dishesCreateListener?.setCassetteNameList(position, foodNameList)
                    dishesCreateListener?.setCassetteValueList(position, foodValueList)
                }
            }
        })


    }

    //添加一项调味料数据
    @SuppressLint("NotifyDataSetChanged")
    private fun addSauceItem(item: DishesCreateBean, position: Int, sauceNameList: MutableList<String>, sauceValueList: MutableList<String>, type: String) {
        when ( type ){
            "新增列表" ->{
                sauceNameList.add("")
                sauceValueList.add("")
                item.sauceNameList = sauceNameList.toMutableList() // 确保同步到item // 同步到DishesCreateBean
                item.sauceValueList = sauceValueList.toMutableList() // 确保同步到item // 同步到DishesCreateBean
                dishesCreateListener?.setNozzleNameList(position, sauceNameList)
                dishesCreateListener?.setNozzleValueList(position, sauceValueList)
                putSauceData(sauceNameList, sauceValueList)
                notifyDataSetChanged()
            }
            "初始化" ->{
                if ( sauceNameList.isEmpty() && sauceValueList.isEmpty() ){
                    sauceNameList.add("")
                    sauceValueList.add("")
                    item.sauceNameList = sauceNameList.toMutableList() // 确保同步到item // 同步到DishesCreateBean
                    item.sauceValueList = sauceValueList.toMutableList() // 确保同步到item // 同步到DishesCreateBean
                    dishesCreateListener?.setNozzleNameList(position, sauceNameList)
                    dishesCreateListener?.setNozzleValueList(position, sauceValueList)
                    putSauceData(sauceNameList, sauceValueList)
                } else {
                    dishesCreateListener?.setNozzleNameList(position, sauceNameList)
                    dishesCreateListener?.setNozzleValueList(position, sauceValueList)
                    putSauceData(sauceNameList, sauceValueList)
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun putSauceData(sauceNameList: MutableList<String>, sauceValueList: MutableList<String>) {
        dishesCreateSauceBeans = getDishesCreateSauceBeansList(sauceNameList, sauceValueList)

        if ( dishesCreateSauceBeans.isEmpty()) {
            dishesCreateSauceList.clear()
        }
        dishesCreateSauceAdapter!!.notifyDataSetChanged()
    }

    private fun getDishesCreateSauceBeansList(sauceNameList: MutableList<String>, sauceValueList: MutableList<String>): MutableList<DishesCreateSauceBean> {
        return try {
            val dishesCreateSauceBeans: MutableList<DishesCreateSauceBean> = mutableListOf()
            if (sauceNameList.isNotEmpty()) {
                for (i in sauceNameList.indices) {
                    val dishesCreateSauceBean = DishesCreateSauceBean(
                        sauceNameList[i],
                        sauceValueList[i],
                    )
                    dishesCreateSauceBeans.add(dishesCreateSauceBean)
                }
                dishesCreateSauceList.clear()
                dishesCreateSauceList.addAll(dishesCreateSauceBeans)
            }
            dishesCreateSauceBeans
        } catch (e: java.lang.Exception) {
            mutableListOf()
        }
    }

    //添加一项食材数据
    private fun addFoodItem(item: DishesCreateBean, position: Int, foodNameList: MutableList<String>, foodValueList: MutableList<String>, type: String) {
        when ( type ){
            "新增列表" ->{
                foodNameList.add("")
                foodValueList.add("")
                item.foodNameList = foodNameList.toMutableList() // 确保同步到item // 同步到DishesCreateBean
                item.foodValueList = foodValueList.toMutableList() // 确保同步到item // 同步到DishesCreateBean
                dishesCreateListener?.setCassetteNameList(position, foodNameList)
                dishesCreateListener?.setCassetteValueList(position, foodValueList)
                putFoodData(foodNameList, foodValueList)
            }
            "初始化" ->{
                if ( foodNameList.isEmpty() || foodValueList.isEmpty() ){
                    if ( foodNameList.isEmpty() ){
                        foodNameList.add("")
                    }
                    if ( foodValueList.isEmpty() ){
                        foodValueList.add("")
                    }
                    item.foodValueList = foodValueList.toMutableList() // 确保同步到item // 同步到DishesCreateBean
                    item.foodValueList = foodValueList.toMutableList() // 确保同步到item // 同步到DishesCreateBean
                    dishesCreateListener?.setCassetteNameList(position, foodNameList)
                    dishesCreateListener?.setCassetteValueList(position, foodValueList)
                    putFoodData(foodNameList, foodValueList)
                } else {
                    dishesCreateListener?.setCassetteNameList(position, foodNameList)
                    dishesCreateListener?.setCassetteValueList(position, foodValueList)
                    putFoodData(foodNameList, foodValueList)
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun putFoodData(foodNameList: MutableList<String>, foodValueList: MutableList<String>) {
        dishesCreateFoodBeans = getDishesCreateFoodBeansList(foodNameList, foodValueList)

        if ( dishesCreateFoodBeans.isEmpty()) {
            dishesCreateFoodList.clear()
        }
        dishesCreateFoodAdapter!!.notifyDataSetChanged()
    }

    private fun getDishesCreateFoodBeansList(foodNameList: MutableList<String>, foodValueList: MutableList<String>): MutableList<DishesCreateFoodBean> {
        return try {
            val dishesCreateFoodBeans: MutableList<DishesCreateFoodBean> = mutableListOf()
            if (foodNameList.isNotEmpty()) {
                for (i in foodNameList.indices) {
                    val dishesCreateFoodBean = DishesCreateFoodBean(
                        foodNameList[i],
                        foodValueList[i],
                    )
                    dishesCreateFoodBeans.add(dishesCreateFoodBean)
                }
                dishesCreateFoodList.clear()
                dishesCreateFoodList.addAll(dishesCreateFoodBeans)
            }
            dishesCreateFoodBeans
        } catch (e: java.lang.Exception) {
            mutableListOf()
        }
    }

    private fun getAddFoodType(type: String): String{
        when ( type ){
            "1" ->{
                return "常规投菜（投两下）"
            }
            "2" ->{
                return "慢速投菜（滞留几秒后归位，不抖动）"
            }
            "3" ->{
                return "快速投菜（投三下）"
            }
            "4" ->{
                return "慢速投菜（投三下）"
            }
        }
        return ""
    }

    private fun getAddFoodColor(type: String): Int{
        if ( type.isNotEmpty() ){
            return "#FFFFFF".toColorInt()
        }
        return "#99FFFFFF".toColorInt()
    }

    @SuppressLint("SetTextI18n")
    //弹出投菜方式弹窗
    private fun showAddFoodDialog(position: Int, holder: AppHolder?, item: DishesCreateBean) {
        val builder: AlertDialog.Builder = AlertDialog.Builder(context)
        builder.setTitle("选择投菜方式")

        val portions = arrayOfNulls<String>(4)
        portions[0] = "常规投菜（投两下）"
        portions[1] = "慢速投菜（滞留几秒后归位，不抖动）"
        portions[2] = "快速投菜（投三下）"
        portions[3] = "慢速投菜（投三下）"

        builder.setItems(portions) { _, which ->
            val selected: Int = which // 获取选中的调味料
            holder?.setText(R.id.adapter_dishes_create_food_general_choose_num, portions[selected])
            holder?.setTextColor(R.id.adapter_dishes_create_food_general_choose_num,
                "#FFFFFF".toColorInt())
            dishesCreateListener?.setAddFood(position, portions[selected]!!)
            item.box_release_type = (selected + 1).toString()
        }

        builder.show()
    }

    @SuppressLint("NotifyDataSetChanged")
    //刷新数据
    fun updateData(newData: List<DishesCreateBean>) {
        //在这里把之前填写过的食材数量统计起来，作为盒子使用数，用于区分不同的投料时间
        foodLength = 0
        for ( i in 0 until newData.size )  {
            if ( newData[i].foodNameList.isNotEmpty() ){
                foodLength++
            }
        }
        (context as? Activity)?.runOnUiThread {
            (mItems as? MutableList)?.apply {
                clear()
                addAll(newData)
            }
            notifyDataSetChanged()
        }
    }
}